import { reactive, ref, nextTick } from 'vue'
import { useForm } from '@/hooks/web/useForm'

// 定义对象的类型
interface Selecter {
  title: string
  code: string
}

export default function (initialStaffList: { countries: Selecter[] }) {
  const { formMethods } = useForm()
  const { getElFormExpose } = formMethods

  const staffList = reactive(initialStaffList)
  const selectedPartner = reactive<Selecter[]>([])
  const partnerDialogVisible = ref(false)

  const handlePartnerButtonClick = (event: MouseEvent) => {
    event.stopPropagation() // 阻止事件冒泡
    partnerDialogVisible.value = true
  }

  const removePartner = (code: string) => {
    const index = selectedPartner.findIndex((item) => item.code === code)
    if (index !== -1) {
      selectedPartner.splice(index, 1)
    }
  }

  const handlePartnerDDDialodConfirm = async (selectedPartnerValues) => {
    // 先清空已选的合作伙伴，以避免重复
    selectedPartner.splice(0, selectedPartner.length)
    // 添加新的合作伙伴
    staffList.countries.forEach((item) => {
      if (selectedPartnerValues.includes(item.code)) {
        selectedPartner.push(item)
      }
    })
    await nextTick() // 等待 DOM 更新
    // 手动触发表单验证
    const elForm = await getElFormExpose()
    elForm?.clearValidate(['partner']) // 清除partner字段的验证结果
    elForm?.validateField('partner')
  }

  return {
    staffList,
    partnerDialogVisible,
    selectedPartner,
    handlePartnerButtonClick,
    removePartner,
    handlePartnerDDDialodConfirm
  }
}
